package com.xof.phonecall.receiver

import android.telephony.PhoneStateListener
import android.telephony.TelephonyManager

class MyPhoneStateListener : PhoneStateListener() {

    var mCurrentState: PhoneCallState = PhoneCallState.CALL_TYPE_IDEL
    var mOldState: PhoneCallState = PhoneCallState.CALL_TYPE_IDEL
    private var mOnActionListener: (PhoneCallState) -> Unit = { item -> }

    override fun onCallStateChanged(state: Int, phoneNumber: String?) {
        super.onCallStateChanged(state, phoneNumber)

        println("state:$state, phone:$phoneNumber")

        when (state) {
            TelephonyManager.CALL_STATE_IDLE -> {
                //0-等待
                mCurrentState = PhoneCallState.CALL_TYPE_IDEL
                mOnActionListener.invoke(mCurrentState)
            }
            TelephonyManager.CALL_STATE_RINGING -> {
                //1-响铃
                mCurrentState = PhoneCallState.CALL_TYPE_RING
            }
            TelephonyManager.CALL_STATE_OFFHOOK -> {
                //2-接通中
                mCurrentState = PhoneCallState.CALL_TYPE_CALING
            }
        }

//        if ((mOldState == PhoneCallState.CALL_TYPE_RING) and
//            (mCurrentState == PhoneCallState.CALL_TYPE_CALING)
//        ) {
//            println("onCallStateChanged: $phoneNumber 正在接听中...")
//
//        } else if ((mOldState == PhoneCallState.CALL_TYPE_CALING) and
//            (mCurrentState == PhoneCallState.CALL_TYPE_IDEL)
//        ) {
//            println("onCallStateChanged: $phoneNumber 已经挂断...")
//        } else if ((mOldState == PhoneCallState.CALL_TYPE_IDEL) and
//            (mCurrentState == PhoneCallState.CALL_TYPE_CALING)
//        ) {
//            println("onCallStateChanged: $phoneNumber 正在拨号...")
//        }
    }

    fun setActionListener(listener: (PhoneCallState) -> Unit) {
        mOnActionListener = listener
    }
}